const express = require('express');
const router = express.Router();
const scheduler = require('../scheduler');
const emailService = require('../utils/emailService');
const excelService = require('../utils/excelService');

// 获取定时任务状态
router.get('/status', (req, res) => {
  try {
    const status = scheduler.getStatus();
    res.json({
      success: true,
      data: status,
      message: '获取定时任务状态成功'
    });
  } catch (error) {
    console.error('获取定时任务状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取定时任务状态失败',
      error: error.message
    });
  }
});

// 手动执行定时任务
router.post('/execute/:taskName', async (req, res) => {
  try {
    const { taskName } = req.params;
    
    // 验证任务名称
    const validTasks = ['update-appointment-pools', 'cleanup-expired-data', 'send-appointment-report', 'check-pool-status'];
    if (!validTasks.includes(taskName)) {
      return res.status(400).json({
        success: false,
        message: '无效的任务名称'
      });
    }
    
    await scheduler.executeTask(taskName);
    
    res.json({
      success: true,
      message: `任务 ${taskName} 执行完成`
    });
  } catch (error) {
    console.error('执行定时任务失败:', error);
    res.status(500).json({
      success: false,
      message: '执行定时任务失败',
      error: error.message
  });
  }
});

// 启动定时任务
router.post('/start', (req, res) => {
  try {
    scheduler.start();
    res.json({
      success: true,
      message: '定时任务启动成功'
    });
  } catch (error) {
    console.error('启动定时任务失败:', error);
    res.status(500).json({
      success: false,
      message: '启动定时任务失败',
      error: error.message
    });
  }
});

// 停止定时任务
router.post('/stop', (req, res) => {
  try {
    scheduler.stop();
    res.json({
      success: true,
      message: '定时任务停止成功'
    });
  } catch (error) {
    console.error('停止定时任务失败:', error);
    res.status(500).json({
      success: false,
      message: '停止定时任务失败',
      error: error.message
    });
  }
});

// 测试邮件发送
router.post('/test-email', async (req, res) => {
  try {
    const { email } = req.body;
    
    if (!email) {
      return res.status(400).json({
        success: false,
        message: '请提供收件人邮箱'
      });
    }
    
    const result = await emailService.sendTestEmail(email);
    
    if (result.success) {
      res.json({
        success: true,
        message: '测试邮件发送成功'
      });
    } else {
      res.status(500).json({
        success: false,
        message: '测试邮件发送失败',
        error: result.error
      });
    }
  } catch (error) {
    console.error('发送测试邮件失败:', error);
    res.status(500).json({
      success: false,
      message: '发送测试邮件失败',
      error: error.message
    });
  }
});

// 手动生成预约数据报告
router.post('/generate-report', async (req, res) => {
  try {
    const { hospitalId, startDate, endDate } = req.body;
    
    if (!hospitalId || !startDate || !endDate) {
      return res.status(400).json({
        success: false,
        message: '请提供医院ID、开始日期和结束日期'
      });
    }
    
    // 获取医院信息
    const { pool } = require('../database');
    const [hospitals] = await pool.execute('SELECT name FROM hospitals WHERE id = ?', [hospitalId]);
    
    if (hospitals.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医院不存在'
      });
    }
    
    // 生成Excel报告
    const report = await excelService.generateAppointmentReport({
      hospitalId,
      startDate,
      endDate,
      hospitalName: hospitals[0].name
    });
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(report.fileName)}"`);
    
    // 发送文件
    res.send(report.buffer);
  } catch (error) {
    console.error('生成预约数据报告失败:', error);
    res.status(500).json({
      success: false,
      message: '生成预约数据报告失败',
      error: error.message
    });
  }
});

// 获取邮件配置
router.get('/email-config', (req, res) => {
  try {
    const config = {
      smtpHost: process.env.SMTP_HOST || 'smtp.qq.com',
      smtpPort: process.env.SMTP_PORT || 587,
      smtpUser: process.env.SMTP_USER || 'your_email@qq.com',
      emailEnabled: process.env.EMAIL_ENABLED === 'true',
      recipientEmail: process.env.EMAIL_RECIPIENT || 'admin@hospital.com'
    };
    
    res.json({
      success: true,
      data: config,
      message: '获取邮件配置成功'
    });
  } catch (error) {
    console.error('获取邮件配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取邮件配置失败',
      error: error.message
    });
  }
});

module.exports = router;
